package com.linkage.linkedlife.common;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.apkfuns.logutils.Constant;
import com.clark.dingding.constants.ARouterPath;
import com.google.gson.Gson;
import com.just.agentweb.AgentWeb;
import com.linkage.linkedlife.model.AgentMsg;

/**
 * Created by cenxiaozhong on 2017/5/14.
 * source code  https://github.com/Justson/AgentWeb
 */

public class AndroidInterface {

    private Handler deliver = new Handler(Looper.getMainLooper());
    private Context context;
    private Gson gson=new Gson();

    public AndroidInterface( Context context) {
        this.context = context;
    }


    @JavascriptInterface
    public void callAndroid(final String msg) {

        deliver.post(new Runnable() {
            @Override
            public void run() {

                Log.i("Info", "main Thread:" + Thread.currentThread()+msg);
//                Toast.makeText(context.getApplicationContext(), "" + msg, Toast.LENGTH_LONG).show();
//                ARouter.getInstance().build(ARouterPath.PageLinkActivity).navigation();
                if(msg.contains("type")){
                    if(gson.fromJson(msg, AgentMsg.class).getType().equals("navigate")){
                        Log.i("Info", "main navigate:" + Thread.currentThread()+msg);
                        ARouter.getInstance().build(ARouterPath.PageLinkActivity)
                                .withString("url",gson.fromJson(msg, AgentMsg.class).getUrl())
                                .withSerializable("msgData",gson.fromJson(msg, AgentMsg.class))
                                .navigation();
                    }
                }


            }
        });


        Log.i("Info", "Thread:" + Thread.currentThread());

    }

    /**
     * 网页使用的js，方法无参数
     */
    @JavascriptInterface
    public void startFunction() {
        Log.e("startFunction", "----无参");
    }

    /**
     * 网页使用的js，方法有参数，且参数名为data
     *
     * @param data 网页js里的参数名
     */
    @JavascriptInterface
    public void startFunction(String data) {
        Log.e("startFunction", "----有参" + data);
    }

}
